#include <iostream>
#include <fcntl.h>
#include <unistd.h>
#include <cerrno>
#include <cstdio>
#include <cstring>
using namespace std;

void SetNonBlock(const int &fd){
    int f1 = fcntl(fd, F_GETFL);
    if(f1<0){
        perror("fcntl");
        return;
    }
    fcntl(fd, F_SETFL, f1 | O_NONBLOCK);
}
int main(){
    char buffer[1024];
    SetNonBlock(0);
    cout << "stdin SetNonBlock done..." << endl;
    sleep(1);
    while(true){
        ssize_t n = read(0, buffer, sizeof(buffer) - 1);
        // 读取成功
        if(n > 0){
            buffer[n - 1] = 0;
            cout << "echo: " << buffer << endl;
        }
        // 读取结束
        else if (n == 0){
            cout << "read done..." << endl;
        }
        // 读取失败
        else{
            // 没有可读数据
            if(errno==EWOULDBLOCK){
                cout << "resource not ready, try again!" << endl;
                sleep(1);
            }
            // 读取错误
            else{
                cout << "read error, n: " << n << " errno code: " << errno << " strerror: " << strerror(errno) << endl;
            }
        }
        sleep(1);
    }

    return 0;
}